package com.xxx.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xxx.system.annotation.PreAuthorize;
import com.xxx.system.jwt.JwtUtil;
import com.xxx.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");  //56d96a2-1e9f-4e7a-a34b-1071a81cd9bf
        String type = request.getHeader("userType");  //56d96a2-1e9f-4e7a-a34b-1071a81cd9bf
        if (!StrUtil.isBlank(type)){
            return true;
        }
        //2.获取redis中的登录信息
        if(token!=null){
            try {
                //解析请求头中的token
                Payload payload = JwtUtil.parseJwtToken(token);
                //判断用户是否有该请求的权限
                //1.获取当前接口需要啥权限
                    //1.1可以拿到即将请求的接口
                HandlerMethod method = (HandlerMethod) handler;
                //2.用户有啥权限
                PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                if (methodAnnotation == null) {
                    return true;
                }
                    //2.1需要权限
                String needPerm = methodAnnotation.sn();
                    //2.2拥有的权限
                List<String> permissions = payload.getPermissions();
                if (needPerm!=""&&permissions!=null&&permissions.size()>0){
                    if (!permissions.contains(needPerm)){
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().println("{\"success\":false,\"message\":\"无权限\"}");
                        return false;
                    }
                }

                return true; //放行 - 没有做刷新过期时间
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
                return false;
            }
            //3.2.不为null=登录了=>放行
        }
        
        //3.1.为null=没有登录或过期了=>想办法跳转登录页面
        //response.sendRedirect("http://localhost:8081/#/login"); - 万一是用户访问
        //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象]
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
        return false;
    }
}